// 实现这个项目的构建任务
const {
  src,
  dest,
  parallel,
  series,
  watch
} = require('gulp')

const del = require('del')
const browserSync = require('browser-sync')

const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins()
const bs = browserSync.create()

const sass = require('gulp-sass')(require('sass'))

const data = require("./src/tools/mork")


const clean = () => {
  return del(['dist', 'temp'])
}

const style = () => {
  return src('src/assets/styles/*.scss', {
      base: 'src'
    })
    .pipe(sass({
      outputStyle: 'expanded'
    }))
    .pipe(dest('temp'))
}

const script = () => {
  return src('src/assets/scripts/*.js', {
      base: 'src'
    })
    .pipe(plugins.babel({
      presets: ['@babel/preset-env']
    }))
    .pipe(dest('temp'))
}

const page = () => {
  return src('src/*.html', {
      base: 'src'
    })
    .pipe(plugins.swig({
      data
    }))
    .pipe(dest('temp'))
}

// 图片转换
const image = () => {
  return src('src/assets/images/**', {
      base: 'src'
    })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const font = () => {
  return src('src/assets/fonts/**', {
      base: 'src'
    })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const extra = () => {
  return src('public/**', {
      base: 'public'
    })
    .pipe(dest('dist'))
}

// 开发服务器
const serve = () => {
  // 监听路径， 可监听后需要执行的任务
  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', script)
  watch('src/*.html', page)
  // watch('src/assets/images/**',image)
  // watch('src/assets/fonts/**',font)
  // watch('public/**',extra)

  watch([
    'src/assets/images/**',
    'src/assets/fonts/**',
    'public/**'
  ], bs.reload)

  bs.init({
    notify: false,
    port: 2021,
    files: 'dist/**', // 监听 dist 文件下面的所有文件，有改动就自动更新
    server: {
      baseDir: ['temp', 'src', 'public'],
      routes: {
        '/node_modules': 'node_modules'
      }
    }
  })

}

// 文件压缩
const useref = () => {
  return src('temp/*.html', {
      base: 'temp'
    })
    .pipe(plugins.useref({
      searchPath: ['temp', '.']
    }))
    // html css js
    // 三种类型，需要判断文件是哪个类型，然后分别操作

    // 匹配 .js结尾就执行后面的转换流
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({
      collapseWhitespace: true, // 压缩空格
      minifyCSS: true, //压缩script标签
      minifyJS: true // 压缩style标签
    })))
    .pipe(dest('dist'))
}
// 并行任务
const compile = parallel(style, script, page)

const build = series(
  clean,
  parallel(
    series(compile, useref),
    image, font, extra)
)

const develop = series(compile, serve)

module.exports = {
  clean,
  build,
  develop
}